﻿using CBS.APP;
using CBS.Model.ViewModel;
using HandyControl.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.FormPage
{
    /// <summary>
    /// AddSemester.xaml 的交互逻辑
    /// </summary>
    public partial class AddSemester : Window
    {
        private bool isEdit = false;
        private int semesterId = 0;
        public AddSemester()
        {
            InitializeComponent();
            
        }

        public AddSemester(int semesterId)
        {
            InitializeComponent();
            try
            {
                isEdit = true;
                this.semesterId = semesterId;

                SemesterViewModel viewModel = SemesterApp.GetForm(semesterId);
                tb_SemesterName.Text = viewModel.SemesterName;
                tb_StartTime.Text = viewModel.StartTime.HasValue ? viewModel.StartTime.Value.ToString("yyyy-MM-dd HH:mm") : "";
                tb_EndTime.Text = viewModel.EndTime.HasValue ? viewModel.EndTime.Value.ToString("yyyy-MM-dd HH:mm") : "";
                tb_Memo.Text = viewModel.Memo;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SemesterViewModel viewModel = new SemesterViewModel();
            viewModel.SemesterName = tb_SemesterName.Text.Trim();
            viewModel.StartTime = string.IsNullOrWhiteSpace(tb_StartTime.Text.Trim())? null : DateTime.Parse(tb_StartTime.Text.Trim());
            viewModel.EndTime = string.IsNullOrWhiteSpace(tb_EndTime.Text.Trim()) ? null : DateTime.Parse(tb_EndTime.Text.Trim());
            viewModel.Memo = tb_Memo.Text.Trim();

            try
            {
                if (isEdit)
                {
                    viewModel.SemesterId = semesterId;
                    if (SemesterApp.UpdateSemester(viewModel))
                    {
                        this.DialogResult = true;
                    }
                    else
                    {
                        this.DialogResult = false;
                    }
                }
                else
                {
                    if (SemesterApp.CreateSemester(viewModel))
                    {
                        this.DialogResult = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }      
        }
    }
}
